package pl.com.qapps.unity;

import java.io.IOException;

import pl.com.qapps.unity.AppIndicator.Category;
import pl.com.qapps.unity.IndicatorPb.IndicatorEvent;
import pl.com.qapps.unity.IndicatorPb.IndicatorEvent.Property;
import pl.com.qapps.unity.IndicatorPb.IndicatorEvent.Value;
import pl.com.qapps.unity.UnityPb.Request;
import pl.com.qapps.unity.UnityPb.Response;

/**
 * @author Jakub Dykowski
 * 
 */
final class IndicatorProxy {

	static {
//		Unity.register(IndicatorPb.indicatorEvent);
		Unity.register(IndicatorPb.indicatorResponse);
	}
	

	IndicatorProxy(String id, String iconName, Category category) {
		if (iconName == null)
			throw new NullPointerException("iconName cannot be null");
		// TODO use id
		// TODO use category
		// TODO use icon name
	}

	Value get(Property property) {
		Response res = send(IndicatorEvent.newBuilder()
				.setName(property)
				.build());

		if (!res.hasExtension(IndicatorPb.indicatorResponse)) {
			throw new IndicatorException("no value returned in response", true);
		}
		return res.getExtension(IndicatorPb.indicatorResponse);
	}

	void set(Property property, Value value) {
		send(IndicatorEvent.newBuilder()
				.setName(property)
				.setValue(value)
				.build());
	}

	private Response send(IndicatorEvent evt) {
		try {
			return Unity.connect().send(
					Request.newBuilder()
							.setExtension(IndicatorPb.indicatorEvent, evt)
							.build());
		} catch (IllegalStateException | IOException e) {
			// TODO make better exception handling
			throw new IndicatorException("internal indicator failure", e);
		} catch (UnityException e) {
			throw new IndicatorException(e);
		}

	}

}
